package com.itheima.service.impl;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserInfoDao;
import com.itheima.domain.Role;
import com.itheima.domain.UserInfo;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userInfoDao.findUserInfoByName(username);
        List<Role> list = userInfo.getList();
             List<SimpleGrantedAuthority> authority = getAuthority(list);
//         "{noop}" +
        User user = new User(userInfo.getUsername(), userInfo.getPassword(),userInfo.getStatus() == 0 ? false : true, true,
                true, true, authority);
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return authorities;
    }


    @Override
    public List<UserInfo> findAll(int page, int pageSize) {
        PageHelper.startPage(page,pageSize);
        return userInfoDao.findAll();
    }

    @Override
    public UserInfo findById(String id) {
                return userInfoDao.findById(id);
    }

    @Override
    public int save(UserInfo userInfo) {
      return   userInfoDao.save(userInfo);
    }

    @Override
    public List<Role> findUserNotRole(String id) {
        return  userInfoDao.findUserNotRole(id);
    }

    @Override
    public int addRoleToUser(String userId, String[] ids) {
        int number=0;
        for (int i = 0; i <ids.length ; i++) {
            String id=ids[i];
          number = userInfoDao.addRoleToUser(userId,id);
        }
        return number;
    }


}
